//调用函数，判断是否有token
checkLogin()

//渲染用户名
renderUsername()

//退出登录
logout()

// const token = localStorage.getItem('token')
// console.log(token)
//获取学生列表
async function renderStudentList() {
    const res = await axios({
        url: '/students',
        method: 'GET',
        /* headers: {
            Authorization: token
        } */
    })
    // console.log(res.data)
    document.querySelector('.total').innerHTML = res.data.length
    const str = res.data.map((item) => {
        // console.log(item)
        const {
            id,
            user_id,
            name,
            age,
            gender,
            area,
            city,
            createdAt,
            group,
            hope_salary,
            province,
            salary,
            updatedAt
        } = item
        return `
        <tr>
    <td>${name}</td>
    <td>${age}</td>
    <td>${gender==0?'男':'女'}</td>
    <td>第${group}组</td>
    <td>${hope_salary}</td>
    <td>${salary}</td>
    <td>${province+city+area}</td>
    <td data-id=${id}>
      <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
       <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
     </td>
</tr> 
        `
    }).join('')
    document.querySelector('.list').innerHTML = str
}

renderStudentList()

// 显示弹框
//找弹窗标签
const modalDom = document.querySelector('#modal')
//创建弹窗对象
const modal = new bootstrap.Modal(modalDom)

//收集数据
// const data = serialize(document.querySelector('.list'), {
//     hash: true,
//     empty: true
// })
// console.log(data)

//增加删除
document.querySelector('.list').addEventListener('click', function (e) {
    // console.log(1111)
    // console.log(e.target.parentNode.parentNode.dataset.id)
    const id = e.target.parentNode.parentNode.dataset.id
    // 修改标题
    document.querySelector('.modal-title').innerText = '修改学员'
    if (e.target.classList.contains('bi-pen')) {
        modal.show()
        // console.log(studentList(id))
        studentList(id).then((res) => {
            const {
                id,
                user_id,
                name,
                age,
                gender,
                area,
                city,
                createdAt,
                group,
                hope_salary,
                province,
                salary,
                updatedAt
            } = res.data;
            document.querySelector('#form').innerHTML =
                `<div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">姓名：</label>
                <input type="text" name="name" class="form-control" placeholder="请输入姓名" value="${name}" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">性别：</label>
                <div class="input">
                  <div class="form-check d-inline-block">
                    <input ${gender === 0? 'checked' : ''}  value="0" checked id="cb01" class="form-check-input" type="radio" name="gender" />
                    <label for="cb01" class="form-check-label">男</label>
                  </div>
                  <div class="form-check d-inline-block">
                    <input ${gender === 1? 'checked' : ''} value="1" id="cb02" class="form-check-input" type="radio" name="gender" />
                    <label for="cb02" class="form-check-label">女</label>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">年龄：</label>
                <input type="text" name="age" class="form-control" placeholder="请输入年龄" value="${age}" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">组号：</label>
                <input type="text" name="group" class="form-control" placeholder="请输入1-8组号" value="${group}"/>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">期望薪资：</label>
                <input type="text" name="hope_salary" class="form-control" placeholder="请输入期望薪资" value="${hope_salary}"/>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">就业薪资：</label>
                <input type="text" name="salary" class="form-control" placeholder="请输入就业薪资" value="${salary}"/>
              </div>
            </div>
            <div class="col-sm-12">
              <div class="form-group">
                <label class="input-group-label">籍贯：</label>
                <div class="input pl-0">
                  <select class="form-select custom-select" name="province">
                    <option value="${province}">${province}</option>
                  </select>
                  <select class="form-select custom-select" name="city">
                    <option value="${city}">${city}</option>
                  </select>
                  <select class="form-select custom-select" name="area">
                    <option value="${area}">${area}</option>
                  </select>
                </div>
              </div>
            </div>
       `

            document.querySelector('#submit').addEventListener('click', async function () {
                //收集数据
                const data = serialize(document.querySelector('#form'), {
                    hash: true,
                    empty: true
                })
                data.age = +data.age
                data.gender = +data.gender
                data.hope_salary = +data.hope_salary
                data.salary = +data.salary
                data.group = +data.group

                const saveRes = await axios({
                    url: `/students/${id}`,
                    method: 'PUT',
                    data
                })
                showToast(saveRes.message)
                renderStudentList()
                modal.hide()
                // console.log(saveRes)
            })

        })
    }

    if (e.target.classList.contains('bi-trash')) {
        del(id)
    }
})

// 删除-学生
function del(id) {
    axios({
        url: `/students/${id}`,
        /*   Path : id */
        /* headers: {
            Authorization: token
        } */
        method: 'DELETE'
    })
    renderStudentList()
}

//获取-学生详情
async function studentList(id) {
    const res = await axios({
        url: `/students/${id}`,
        method: 'GET'
    })
    return res
}
// studentList(2329999)

// let student = studentList(2329999)
// student.then((res) => {
//     const data = res.data;
//     console.log(data)
// })


//修改-学生详情
// function update(id) {
//     axios({
//         url: `/students/${id}`,
//         method: 'PUT',
//         data
//     })
// }

// console.log(update(2329999))


//添加-学生
document.querySelector('#openModal').addEventListener('click', function () {
    document.querySelector('.modal-title').innerHTML = '添加学生'
    document.querySelector('#submit').addEventListener('click', async function () {
        //收集数据
        const data = serialize(document.querySelector('#form'), {
            hash: true,
            empty: true
        })
        // console.log(data)
        data.age = +data.age
        data.gender = +data.gender
        data.hope_salary = +data.hope_salary
        data.salary = +data.salary
        data.group = +data.group
        const res = await axios({
            url: '/students',
            method: 'POST',
            data
        })
        // console.log(res)
        showToast(res.message)
        modal.hide()
        renderStudentList()
        document.querySelector('[name=name]').innerText = ''
        document.querySelector('[name=age]').innerText = ''

    })
    modal.show()
})

//清空数据
function datas() {
    document.querySelector('[name=name]').innerText = ''
    document.querySelector('[name=age]').innerText = ''

}



async function initSelect() {
    // 省数据获取+渲染
    const res1 = await axios.get('/api/province')
    console.log(res1)
    const str1 = res1.list.map(item => {
        return `<option value="${item}">${item}</option>`
    }).join('')
    document.querySelector('[name=province]').innerHTML = `<option value="">--省份--</option>${str1}`

    // 市数据获取+渲染
    let pname = ''
    console.log(pname)
    document.querySelector('[name=province]').addEventListener('change', async function () {
        pname = this.value
        const res2 = await axios.get('/api/city', {
            params: {
                pname
            }
        })
        const str2 = res2.list.map((item) => {
            return `<option value="${item}">${item}</option>`
        })

        document.querySelector('[name=city]').innerHTML = `<option value="">--城市--</option>${str2}`
    })

    let cname = ''
    // 区数据获取+渲染
    document.querySelector('[name=city]').addEventListener('change', async function () {
        cname = this.value
        const res3 = await axios.get('/api/area', {
            params: {
                pname,
                cname
            }
        })
        const str3 = res3.list.map((item) => {
            return `<option value="${item}">${item}</option>`
        })
        document.querySelector('[name=area]').innerHTML = `<option value="">--地区--</option>${str3}`
    })
}
initSelect()

async function addStudent() {
    await axios({
        url: '/students',
        data
    })
}